<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <!-- 避免IE使用兼容模式 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="renderer" content="webkit">
    <!-- TopJUI框架样式 -->
    <link type="text/css" href="/static/topjui/themes/default/topjui.core.min.css" rel="stylesheet">
    <link type="text/css" href="/static/topjui/themes/default/topjui.blue.css" rel="stylesheet" id="dynamicTheme"/>
    <!-- FontAwesome字体图标 -->
    <link type="text/css" href="/static/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
    <!-- layui框架样式 -->
    <link type="text/css" href="/static/plugins/layui/css/layui.css" rel="stylesheet"/>
    <!-- jQuery相关引用 -->
    <script type="text/javascript" src="/static/plugins/jquery/jquery.min.js"></script>
    <script type="text/javascript" src="/static/plugins/jquery/jquery.cookie.js"></script>
    <!-- TopJUI框架配置 -->
    <script type="text/javascript" src="/static/public/js/topjui.config.js"></script>
    <!-- TopJUI框架核心-->
    <script type="text/javascript" src="/static/topjui/js/topjui.core.min.js"></script>
    <!-- TopJUI中文支持 -->
    <script type="text/javascript" src="/static/topjui/js/locale/topjui.lang.zh_CN.js"></script>
    <!-- layui框架js -->
    <script type="text/javascript" src="/static/plugins/layui/layui.js" charset="utf-8"></script>
</head>

<body>

<div data-toggle="topjui-layout" data-options="fit:true">
    <div data-options="region:'west',title:'',split:true,border:false,width:'30%',headerCls:'border_right',bodyCls:'border_right'">
        <!-- treegrid表格 -->

        <table data-toggle="topjui-datagrid"
               data-options="id:'sRoleDg',
                    reloadAfterSave:true,
                    selectOnCheck:true,
                    checkOnSelect:true,
                    url:'/sRole/data',
                    pageSize: 10,
                    childGrid:{
                        param:'roleCde:roleCde',
                        grid:[
                            {type:'treegrid',id:'sRescTg'}
                        ]
                    }">
            <thead>
            <tr>
                <th data-options="field:'roleCde',title:'角色代码'"></th>
                <th data-options="field:'roleName',title:'角色名称',width:100"></th>
                <th data-options="field:'roleStsText',title:'角色状态',width:100"></th>
            </tr>
            </thead>
        </table>

    </div>
    <div data-options="region:'center',iconCls:'icon-reload',title:'',split:true,border:false,bodyCls:'border_left'">
        <div data-toggle="topjui-tabs"
             data-options="id:'centerTabs',
                 fit:true,
                 border:false,
                 parentGrid:{
                     type:'treegrid',
                     id:'sRoleDg',
                     param:'roleCde:roleCde'
                 }">
            <!-- 功能权限表格 -->
            <div title="资源列表" data-options="id:'tab0',iconCls:'fa fa-th'">
                <table data-toggle="topjui-treegrid"
                       data-options="id:'sRescTg',
                                        idField:'id',
                                        treeField:'text',
                                        expandAll:true,
                                        singleSelect:true,
                                        checkbox:true,
                                        url:'/sRoleResc/menu',
                                        expandUrl:'/sRoleResc/menu?menuId={id}',
                                        fitColumns:true">
                    <thead>
                    <tr>
                        <!-- <th data-options="field:'uuid',title:'UUID',checkbox:true"></th>-->
                        <th data-options="field:'text',title:'名称',width:200"></th>
                        <th data-options="field:'url',title:'资源地址',width:100"></th>
                        <th data-options="field:'id',title:'编号',width:100"></th>
                        <!-- <th data-options="field:'pid',title:'父级编号',width:100"></th>-->
                        <!--<th data-options="field:'sort',title:'排序',width:50"></th>
                        <th data-options="field:'iconCls',title:'资源图标',width:100"></th>
                        <th data-options="field:'state',title:'资源类别',width:100,hidden:true"></th>-->
                        <th data-options="field:'stateText',title:'类别'"></th>
                        <th data-options="field:'roleCde',title:'角色编号',hidden:true"></th>
                        <th data-options="field:'grantSts',title:'授权状态',
                            formatter: function(value,row,index){
                                if (value == 'A'){
                                    return '<span style=\'color:green\'>已授权</span>';
                                } else {
                                    return '<span style=\'color:red\'>未授权</span>';
                                }
                            }"></th>
                        <th data-options="field:'opt',title:'操作',width:100,formatter: function(value,row,index){
                                if (row.grantSts == 'A'){
                                    return '<span data-rolecde=\''+row.roleCde+'\' data-id=\''+row.id+'\'	class=\'singleUnGrant layui-btn layui-btn-xs  layui-btn-primary\'><i class=\'fa fa-times\'></i> 取消</span>';
                                } else {
                                    return '<span data-rolecde=\''+row.roleCde+'\' data-id=\''+row.id+'\'	class=\'singleGrant layui-btn layui-btn-xs \'><i class=\'fa fa-check\'></i> 授权</span>';
                                }
                            }"></th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>

    </div>

    <!-- authAccessTreegrid 工具栏 -->
    <div id="sRescTg-toolbar" class="topjui-toolbar">

        <a href="javascript:void(0)"
           data-toggle="topjui-menubutton"
           data-options="
                       iconCls:'fa fa-plus',
                       btnCls:'topjui-btn-green',
                       onClick:permissionOnclick
                       ">批量授权</a>


        <a href="javascript:void(0)"
           data-toggle="topjui-menubutton"
           data-options="
                       iconCls:'fa fa-trash',
                       btnCls:'topjui-btn-red',
                       onClick:unPermissionOnclick">批量取消</a>

    </div>


    <!--数据权限工具栏-->
    <div id="sysDataAuthGroupDg-toolbar" class="topjui-toolbar">
        <a href="javascript:void(0)"
           data-toggle="topjui-menubutton"
           data-options="
                       iconCls:'fa fa-plus',
                       btnCls:'topjui-btn-green',
                       onClick:addRule
                       ">批量授权</a>
        <a href="javascript:void(0)"
           data-toggle="topjui-menubutton"
           data-options="
                   iconCls:'fa fa-trash',
                   btnCls:'topjui-btn-red',
                   onClick:cancelRule">批量取消</a>
    </div>
</div>

<!-- 存放具体业务页面需要引入的javascript文件 -->

<script>
    // 定义选择器
    var SELECTOR = {
        sRoleDgSelector: '#sRoleDg', // 左边表格
        sRescTgSelector: '#sRescTg',// 右边表格
        userDgSelector: '#sRescTg', // 数据表格的选择器
        sysDataAuthGroupDgSelector: '#sRescTg' // 数据表格的选择器
    };
    // 定义 URL
    var SCOPE = {
        permissionUrl: "/sRoleResc/save?flag=add", // 授予赋权的URL
        unPermissionUrl: '/sRoleResc/save?flag=remove', // 取消赋权的URL
        addMemberUrl: '/system/authGroup/addRoleMember', // 添加授权人员的URL
        removeMemberUrl: '/system/authGroup/removeRoleMember', // 删除授权人员的URL
        addRuleUrl: '/system/sysDataAuth/addRule',// 添加数据权限
        removeRuleUrl: '/system/sysDataAuth/cancelRule',// 移除数据权限
    };
    // 定义提示消息
    var MSG = {
        permissionSuccess: '赋予授权成功！',
        permissionFail: '赋予授权失败！',
        unPermissionSuccess: "取消授权成功!",
        unPermissionFail: '取消授权失败！'
    };

    /**
     * 授权按钮点击的时候触发
     */
    function permissionOnclick() {
        permissionHandle(1)
    }

    function unPermissionOnclick() {
        $.iMessager.confirm('确认对话框', '确定要执行该操作吗？', function (r) {
            if (r) {
                permissionHandle(0)
            }
        });
    }

    function permissionHandle(param) {
        var $sRoleDg = $(SELECTOR.sRoleDgSelector);
        var $authAccess = $(SELECTOR.sRescTgSelector);
        // 1.获取表格选中的数据
        var postData = getAuthChecked($sRoleDg, $authAccess);
        if (!postData) {
            return;
        }
        // 2.发送赋权请求
        // var url = (param ? SCOPE.permissionUrl : SCOPE.unPermissionUrl) + '?roleId=' + postData.roleId;
        var url = (param ? SCOPE.permissionUrl : SCOPE.unPermissionUrl);
        // var groupSelectedRow = $('#groupTreegrid').iTreegrid("getSelected");
        $.iMessager.progress({title: "提示", text: '请等待……'});
        sendGrantRequest(url, postData, param);
    }


    /**
     * 发送请求
     */
    function sendGrantRequest(url, postData, isGrant, dgSelector) {
        $.post(url, {roleCde: postData.roleCde, rescCde: postData.rescCde}, function (res) {
            if (res.statusCode == 200) {
                //更新节点信息
                var $authAccess = $(dgSelector ? dgSelector : SELECTOR.sRescTgSelector);
                $authAccess.treegrid('reload');// 刷新下表格数据
                //提示
                $.iMessager.show({
                    title: '提示消息',
                    msg: isGrant ? MSG.permissionSuccess : MSG.unPermissionSuccess,
                    timeout: 1000,
                    showType: 'slide'
                });
            } else {
                $.iMessager.alert('提示', res.message ? res.message : (isGrant ? MSG.permissionFail : MSG.unPermissionFail), 'messager-error');
            }
            $.iMessager.progress("close");
        }, 'JSON')
    }

    /**
     * 获取表格选中的数据
     * @param $groupTg
     * @param $authAccess
     * @returns {{roleId: *}}
     */
    function getAuthChecked($groupTg, $authAccess) {
        // 1.判断左边的角色权限是否勾选
        var roleCde = getGroupTgSelectedRoleId();
        if (!roleCde) {
            return;
        }
        // 2.判断右侧是否有选中行
        var authSelectedRow = $authAccess.iTreegrid("getCheckedNodes");
        if (authSelectedRow.length == 0) {
            $.iMessager.alert('提示', '请勾选授权的菜单或规则！', 'messager-info');
            return;
        }
        // 3.获取左侧的数据的角色ID
        var data = {
            roleCde: roleCde
        };
        // 4.获取右侧勾选的ID
        var rescCdeStr = '';
        $.each(authSelectedRow, function (i) {
            if (authSelectedRow[i].id) {
                rescCdeStr += authSelectedRow[i].id;
                if (authSelectedRow.length != i + 1) {
                    rescCdeStr += ','
                }
            }
        });
        data.rescCde = rescCdeStr;
        return data;
    }


    var originalData = '';// 保存原始数据，方便做本地查询
    //过滤
    function authAccessTreegridLoadFilter(data, parentId) {
        var topId1 = '';
        var data = $.formateTreeData(data, 'text', 'id', 'pid'); // 将list中 motool字段赋值给text字段，''代表id字段数据里面有不用转，将里面的'pId'字段转为’pid‘
        var rootNodeId = "1";//需要的顶级节点
        originalData = $.getTreeList($.extend(true, [], data), rootNodeId);//对象克隆
        data = $.getTreeList(data, parentId ? parentId : rootNodeId);// 这个方法两个参数 data 和根节点id 会将数据格式化成标准格式 {id：xxx,pid:xxx,text:xxx,children:[{}……]}

        // 1.新的数据集合
        return data;
    }

    /**
     * 单个授权
     */
    $("body").on("click", ".singleGrant", function () {
        var roleCde = $(this).data("rolecde");
        var id = $(this).data("id");
        sendGrantRequest(SCOPE.permissionUrl, {roleCde: roleCde, rescCde: id}, true, SELECTOR.sRescTgSelector);

    });
    /**
     * 单个取消授权
     */
    $("body").on("click", ".singleUnGrant", function () {
        var id = $(this).data("id");
        var roleCde = $(this).data("rolecde");
        sendGrantRequest(SCOPE.unPermissionUrl, {roleCde: roleCde, rescCde: id}, false, SELECTOR.sRescTgSelector);
    });

    /*
    * 判断左侧是否勾选角色
    */
    function getGroupTgSelectedRoleId() {
        // 1.判断左边的角色权限是否勾选
        var $sRoleDg = $(SELECTOR.sRoleDgSelector);
        var roleSelectedRow = $sRoleDg.iTreegrid("getSelected");
        if (!roleSelectedRow) {
            $.iMessager.alert('提示', '请选择左边的角色！', 'messager-info');
            return;
        } else {
            return roleSelectedRow.roleCde;
        }
    }

    /**
     * 添加授权规则
     */
    function addRule() {
        var $groupTg = $(SELECTOR.sRoleDgSelector);
        var $authAccess = $(SELECTOR.sysDataAuthGroupDgSelector);
        // 1.获取表格选中的数据
        var postData = getAuthChecked($groupTg, $authAccess);
        if (!postData) {
            return;
        }
        // 发送赋值请求
        $.iMessager.progress({title: "提示", text: '请等待……'});
        sendGrantRequest(SCOPE.addRuleUrl, postData, true, SELECTOR.sysDataAuthGroupDgSelector);
    }

    /**
     *取消授权规则
     */
    function cancelRule() {
        var $groupTg = $(SELECTOR.sRoleDgSelector);
        var $authAccess = $(SELECTOR.sysDataAuthGroupDgSelector);
        // 1.获取表格选中的数据
        var postData = getAuthChecked($groupTg, $authAccess);
        if (!postData) {
            return;
        }
        $.iMessager.progress({title: "提示", text: '请等待……'});
        sendGrantRequest(SCOPE.removeRuleUrl, postData, false, SELECTOR.sysDataAuthGroupDgSelector);
    }


    $.extend($.fn.treegrid.methods, {
        //iscontains是否包含父节点（即子节点被选中时是否也取父节点）
        getAllChecked: function (jq, iscontains) {
            var keyValues = new Array();
            /*
              tree-checkbox2 有子节点被选中的css
              tree-checkbox1 节点被选中的css
              tree-checkbox0 节点未选中的css
            */
            var checkNodes = jq.treegrid("getPanel").find(".tree-checkbox1");
            for (var i = 0; i < checkNodes.length; i++) {
                var keyValue1 = $($(checkNodes[i]).closest('tr')[0]).attr("node-id");
                keyValues.push(keyValue1);
            }

            if (iscontains) {
                var childCheckNodes = jq.treegrid("getPanel").find(".tree-checkbox2");
                for (var i = 0; i < childCheckNodes.length; i++) {
                    var keyValue2 = $($(childCheckNodes[i]).closest('tr')[0]).attr("node-id");
                    keyValues.push(keyValue2);
                }
            }

            return keyValues;
        }
    })

</script>
<!--<script>
    var flag = true

    //勾选
    function groupTreegridOnCheck(index, checked) {
        if (!checked) {
            groupTreegridUncheck(index, checked);
            return;
        }
        if (!flag) {
            flag = true
            return;
        }
        try {
            flag = false
            var tg = $("#groupTreegrid").iTreegrid("getParent", index.id);//获取父亲节点
            var children = $("#groupTreegrid").iTreegrid("getChildren", index.id);//获取孩子节点
            for (var i = 0; i < children.length; i++) {
                $("#groupTreegrid").iTreegrid("checkNode", children[i].id)
            }
            $("#groupTreegrid").iTreegrid("checkNode", tg.id)

        } catch (e) {
            console.log("error");
        } finally {
            flag = true;
        }
    }

    //取消
    function groupTreegridUncheck(index, checked) {

        var tg = $("#groupTreegrid").iTreegrid("getParent", index.id);//获取父亲节点
        var children = $("#groupTreegrid").iTreegrid("getChildren", index.id);//获取孩子节点

        if (children.length > 0 && tg == null) {//没有父节点但是有孩子节点
            for (var i = 0; i < children.length; i++) {
                $("#groupTreegrid").iTreegrid("uncheckNode", children[i].id)
            }
        }
        if (children.length > 0 && tg != null) {
            for (var i = 0; i < children.length; i++) {
                $("#groupTreegrid").iTreegrid("uncheckNode", children[i].id)
            }
        }
    }


    function addSubRole() {
        var uuid = $('#uuids').val();
        var status = $('#status').val();
        var pid = $('#pid').val();
        var menuId = $('#menuId').val();
        var state = $('#state').val();
        var sort = $('#sort').val();
        var remark = $('#remark').val();
        var text = $('#text').val();
        var id = $('#id').val();
        var levelId = $('#levelId').val();
        var creatorOrgId = $('#creatorOrgId').val();

        $.ajax({
            url: '/system/authGroup/save',
            data: {
                uuid:uuid,
                status:status,
                pid:pid,
                menuId:menuId,
                state:state,
                sort:sort,
                remark:remark,
                id:id,
                text:text,
                levelId:levelId,
                creatorOrgId:creatorOrgId
            },
            dataType: 'JSON',
            type: 'POST',
            async: false,
            success: function (res) {
                console.log(res)
                if (1 == res) {
                    $.iMessager.show({
                        title: '我的消息',
                        msg: '添加成功',
                        timeout: 1000,
                        showType: 'slide'
                    });
                    $('#TopicgroupAddDialog').iDialog('close');
                    $('#groupTreegrid').iTreegrid('options').url='/system/authGroup/getListByUserUuid';
                    $('#groupTreegrid').iTreegrid('reload');
                } else {
                    $.iMessager.alert({
                        title: '我的消息',
                        msg: '添加失败',
                        timeout: 1000,
                        showType: 'slide'
                    });
                    $.iMessager.progress('close');
                }

            }
        })
    }
    var uuids = []
    function onCheck(row,index){
        console.log(row)
        uuids.push(row.uuid)
    }

</script>-->
<!--<script src="../../static/js/security/mainframe.js"-->
<!--th:src="@{/js/security/mainframe.js}"></script>-->

</body>

</html>